# coding=utf-8
"""
作者：董新强 
创建时间：2020-12-07
描述：应用管理
"""
import time

from enums.enum_error_type import EnumErrorType
from framework.aes_cypto import AesCrypto
from framework.msg import failure, ok
from framework.utilities import to_dict, to_sha256, to_string, get_len, get_random_chars
from services.applications import get_allow_ips


class ApplicationManage:

    @staticmethod
    def decrypt(token, ip):
        """
        解密服务器发送来的数据
        """
        try:
            if get_len(token) < 32: return failure(msg='请登录')
            app_key, enc = token[:32], token[32:]
            if not enc: return failure(msg='请登录')

            # 检测 IP
            key_ips = get_allow_ips(app_key)
            if not key_ips: return failure(msg='请将IP添加到白名单')

            app_id, app_secret, ips = key_ips
            if ip not in ips: return failure(msg='IP不在白名单中')

            dic = to_dict(AesCrypto(app_secret).decrypt(enc))
            return ok(data=(app_id, dic['time']))

        except Exception as e:
            print('ApplicationManage.decrypt=>', e)
            return failure(msg='没有权限', error_type=EnumErrorType.interal_error)

    @staticmethod
    def login(key, randstr, sha, ip):
        try:
            # 检测 IP
            key_ips = get_allow_ips(key)
            if not key_ips: return failure(msg='请将IP添加到白名单')

            app_id, app_secret, ips = key_ips
            if ip not in ips: return failure(msg='IP不在白名单中')

            enc = to_sha256('{}{}{}'.format(key, app_secret, randstr))
            if enc != sha: return failure(msg='登录失败')

            token = {
                'time': int(time.time()),
                'key': key,
                'ip': ip,
                'rand': get_random_chars(6)
            }
            return ok(data={'token': '{}{}'.format(key, AesCrypto(app_secret).encrypt(to_string(token)))})
        except Exception as e:
            return failure(msg='登录失败')
